import { initData } from '@/api/data'

export default {
	data () {
		return {
			data: [],
			// 页码
			page: 1,
			// 每页数据条数
			size: 10,
			// 总数据条数
			total: 0,
			// 请求数据的url
			url: '',
			// 查询数据的参数
			params: {},
			// 待查询的对象
			query: {},
			//加载状态
			loading: false
		}
	},
	methods: {
		async init () {
			return new Promise((resolve, reject) => {
				this.loading = true
				// 请求数据
				initData(this.url, this.getQueryParame()).then(data => {
					const totalElements = data.page.total
					const content = data.items
					this.total = totalElements// data.totalElements
					this.data = content// data.content
					// time 毫秒后显示表格
					setTimeout(() => {
						this.loading = false
					}, this.time)
					resolve(data)
				}).catch(err => {
					this.loading = false
					reject(err)
				})
			})
		},
		beforeInit () {
			return true
		},
		getQueryParame: function () {
			let param = {
				page: this.page,
				size: this.size,
				sort: this.sort,
				...this.query,
				...this.params
			}
			return this.delEmptyQueryNodes(param);

		},
		delEmptyQueryNodes: function (data) {
			let curVal;
			let toString = Object.prototype.toString;
			let dataType = toString.call(data);
			if (data || dataType === "[object Number]" || dataType === "[object Boolean]") {
				switch (dataType) {
					case "[object Object]":
						if (Object.keys(data).length > 0) {
							let momObj = {};
							for (let key in data) {
								let value = this.delEmptyQueryNodes(data[key]);
								let valueType = toString.call(value);
								valueType === "[object Boolean]" || valueType === "[object Number]" || value ? momObj[key] = value : "";
							}
							curVal = momObj;
						} else {
							return;
						}
						break;
					case "[object Array]":
						if (data.length > 0) {
							let momValue = [];
							data.forEach((e) => {
								let value = this.delEmptyQueryNodes(e);
								let valueType = toString.call(value);
								valueType === "[object Boolean]" || valueType === "[object Number]" || value ? momValue.push(value) : "";
							});
							momValue.length > 0 ? curVal = momValue : "";
						} else {
							return;
						}
						break;
					case "[object Boolean]":
					default:
						curVal = data;
						break;
				}
			} else {
				return;
			}
			return curVal;
		},
		// 改变页码
		pageChange (e) {
			this.page = e
			this.init()
		},
		// 改变每页显示数
		sizeChange (e) {
			this.page = 1
			this.size = e
			this.init()
		},
		// 预防删除第二页最后一条数据时，或者多选删除第二页的数据时，页码错误导致请求无数据
		dleChangePage (size) {
			if (size === undefined) {
				size = 1
			}
			if (this.data.length === size && this.page !== 0) {
				this.page = this.page
			}
		},
		// 查询方法
		toQuery () {
			this.page = 1
			this.init()
		},
		notify (title, type) {
			this.$notify({
				title: title,
				type: type,
				duration: 2500
			})
		},
	}
}
